import os
import shutil
from Cheetah.Template import Template
import Lise
import LiseDigi
import Error
import MacFinderColourFile



class LiseWeb(LiseDigi.LiseDigi):
    """
    Implements the operations related to generate a website from a LiSe definition

    """

    def __init__(self, lisePath):
        """Arguments:
        lisePath(string) -- LiSe XML file path

        """
        LiseDigi.LiseDigi.__init__(self, lisePath)



    def _fillNameSpaceForSelectedPage(self, nameSpace, frameIndex, n, webNumberOfPages, langId, zoomId, digiFilename):
        content = {}
        if langId == 'es':
            content['linkEs'] = None
            content['linkEn'] = os.path.join('../..', 'html_en', zoomId, frameIndex + '.html')
        else:
            content['linkEs'] = os.path.join('../..', 'html_es', zoomId, frameIndex + '.html')
            content['linkEn'] = None
        content['cursorFirstRelPath'] = 'index.html'
        content['cursorPreviousRelPath'] = 'page' + str(n-1).zfill(4)  + '.html'
        content['cursorNextRelPath'] = 'page' + str(n+1).zfill(4)  + '.html'
        content['cursorLastRelPath'] = 'page' + str(webNumberOfPages).zfill(4) + '.html'
        html = {} 
        if zoomId == 'thumb':
            html['zoomRelPath'] = os.path.join('../zoom', frameIndex + '.html')
        else:
            html['zoomRelPath'] = os.path.join('../thumb', frameIndex + '.html')
        html['frameIndex'] = frameIndex 
        html['frameHeaderRelPath'] = 'index_header.html'
        html['frameMiddleRelPath'] = frameIndex + '_middle.html'
        html['frameFooterRelPath'] = 'index_footer.html'
        html['frameMenuRelPath'] = frameIndex + '_menu.html'
        html['frameContentRelPath'] = frameIndex + '_content.html'
        html['frameCursorsRelPath'] = frameIndex + '_cursors.html'
        html['stylesPath'] = '../../styles'

        if digiFilename is not None:
            html['framePictureRelPath'] = frameIndex + '_picture.html'
            content['imgRelPath'] = os.path.join('../..', self.digiSubdir, digiFilename)
        else:
            content['imgRelPath'] = None
        if zoomId == 'thumb':
            content['imgCssStyle'] = 'height: 400px'
        else:
            content['imgCssStyle'] = ''

        nameSpace['content'] = content
        nameSpace['html'] = html 

    def _generateWebpage(self, templatePath, nameSpace, outputPath):
        t = Template(file=templatePath, searchList=nameSpace)
        f = open(outputPath, 'w')
        f.write(str(t))
        f.close()

    def _generatePageWebFiles(self, nameSpace, templateDirPath, outputPath, langId, zoomId, frameKeys):
        """

        """
        nameSpace['html']['title'] = ''
        self._generateWebpage(os.path.join(templateDirPath, 'index_html.tmpl'), [nameSpace], 
                              os.path.join(outputPath, 'html_'+langId, zoomId, nameSpace['html']['frameIndex']+'.html'))
        for key in ['middle', 'menu', 'content', 'cursors'] + frameKeys:
            self._generateWebpage(os.path.join(templateDirPath, key+'_html.tmpl'), [nameSpace], 
                                  os.path.join(outputPath, 'html_'+langId, zoomId, nameSpace['html']['frameIndex']+'_'+key+'.html'))
#        t = Template(file=os.path.join(templateDirPath, 'index_html.tmpl'), searchList=[nameSpace])
#        f = open(os.path.join(outputPath, 'html_' + langId, zoomId, nameSpace['html']['frameIndex'] + '.html'), 'w')
#        f.write(str(t))
#        f.close()
#        for key in ['middle', 'menu', 'content', 'cursors']:
#            t = Template(file=os.path.join(templateDirPath, key + '_html.tmpl'), searchList=[nameSpace])
#            f = open(os.path.join(outputPath, 'html_' + langId, zoomId, nameSpace['html']['frameIndex'] + '_' + key + '.html'), 'w')
#            f.write(str(t))
#            f.close()
#        for key in frameKeys:
#            t = Template(file=os.path.join(templateDirPath, key + '_html.tmpl'), searchList=[nameSpace])
#            f = open(os.path.join(outputPath, 'html_' + langId, zoomId, nameSpace['html']['frameIndex'] + '_' + key + '.html'), 'w')
#            f.write(str(t))
#            f.close()

    def _generateMainIndexWebpage(self, templateDirPath, outputPath):
        html = {} 
        html['title'] = ''
        html['frameHeaderRelPath'] = 'html_es/thumb/index_header.html'
        html['frameMiddleRelPath'] = 'html_es/thumb/index_middle.html'
        html['frameFooterRelPath'] = 'html_es/thumb/index_footer.html'
        html['stylesPath'] = 'styles'
        nameSpace = {'html':html}
        self._generateWebpage(os.path.join(templateDirPath, 'index_html.tmpl'), [nameSpace], 
                              os.path.join(outputPath, 'index.html'))
        MacFinderColourFile.MacFinderColourFile([os.path.join(outputPath, 'index.html')], MacFinderColourFile.LABEL_GREEN)

    def GenerateWebsite(self, outputPath=None):
        """

        """
        try:
            self.readDigiSubdir()
        except:
            raise
#        if (self.metadata['es'].getNumberOfPages() != self.metadata['en'].getNumberOfPages()):
#            raise Error.Error(401, 'There is a different number of pages defined in the index of each language')
#        elif (self.metadata['es'].getNumberOfPictures() > len(self.digiFilenames)):
#            raise Error.Error(402, 'There are more pictures defined in the Spanish index than the number of digitised pictures')
#        elif (self.metadata['en'].getNumberOfPictures() > len(self.digiFilenames)):
#            raise Error.Error(403, 'There are more pictures defined in the English index than the number of digitised pictures')
        if outputPath is None:
            outputPath = os.path.dirname(self.lisePath)
        templateDirPath = os.path.join(self._determine_path(), 'templates', 'website', str(self.templateId))
        nameSpace = self.toNameSpace(False, False)
        nameSpace['metadata'] = {}
        for langId in self.metadata.keys():
            # Si hay menos entradas en el indice que imagenes digitalizadas
            numberOfPictures = self.metadata[langId].getNumberOfPictures()
            removeLastInterval = False
            if numberOfPictures < len(self.digiFilenames):
                # Anade temportalmente un intervalo en el indice que compensa la diferencia
                liseInterval = Lise.LiseInterval(numberOfPictures+1, len(self.digiFilenames), '[auto generated ', ']')
                self.metadata[langId].index.append(liseInterval)
                removeLastInterval = True
            nameSpace['metadata'][langId] = self.metadata[langId].toNameSpace(False, False)
            if not os.path.exists(os.path.join(outputPath, 'html_' + langId)):
                os.mkdir(os.path.join(outputPath, 'html_' + langId))
            nameSpace['langId'] = langId
            for zoomId in ['thumb', 'zoom']:
                if not os.path.exists(os.path.join(outputPath, 'html_' + langId, zoomId)):
                    os.mkdir(os.path.join(outputPath, 'html_' + langId, zoomId))
                webNumberOfPages = self.metadata[langId].getNumberOfPages()
                nPicture = 0
                for p in range(0, webNumberOfPages):
                    indexMenu = self.metadata[langId].getIndexMenu(p)
                    frameKeys = []
                    for page in indexMenu:
                        page['htmlRelPath'] = 'page' + str(page['n']).zfill(4) + '.html#anchor'
                        if (page['n'] == 0):
                            page['htmlRelPath'] = 'index.html'
                        if page['type'] == 'chapter_opened' or page['type'] == 'chapter_closed':
                            page['pageTitle'] = page['chapterTitle']
                        if 'selected' in page and page['type'] == 'page':
                            frameIndex = 'page' + str(page['n']).zfill(4)
                            if (p == 0):
                                frameIndex = 'index'
                                frameKeys.append('header')
                                frameKeys.append('footer')
                            if page['picturesPerPage'] > 0:
                                digiFilename = self.digiFilenames[nPicture] if nPicture < len(self.digiFilenames) else ''
                                frameKeys.append('picture')
                            else:
                                digiFilename = None
                            #self._fillNameSpaceForSelectedPage(nameSpace, frameIndex, page['n'], webNumberOfPages-1, langId, zoomId, nameSpace['pictures'][page['n']])
                            self._fillNameSpaceForSelectedPage(nameSpace, frameIndex, page['n'], webNumberOfPages-1, langId, zoomId, digiFilename)
                            if page['notes'] is not None and len(page['notes']) > 0:
                                nameSpace['content']['notes'] = page['notes']
                                if page['notesStyle'] is not None:
                                    nameSpace['content']['notesStyle'] = str(page['notesStyle']) + 'px'
                                else:
                                    nameSpace['content']['notesStyle'] = '20px'
                                nameSpace['html']['frameNotesRelPath'] = frameIndex + '_notes.html'
                                frameKeys.append('notes')
                                if 'notesCssHeight' in page and page['notesCssHeight'] is not None:
                                    if page['picturesPerPage'] > 0:
                                        nameSpace['content']['notesCssHeight'] = page['notesCssHeight']
                                    else:
                                        nameSpace['content']['notesCssPaddingTop'] = str(page['notesCssHeight']) + 'px'
                            nPicture += page['picturesPerPage']
                            if p == 0:
#                               self._fillNameSpaceForSelectedPage(nameSpace, 0, 'index', webNumberOfPages, None, langId, zoomId)
                                nameSpace['content']['cursorFirstRelPath'] = None
                                nameSpace['content']['cursorPreviousRelPath'] = None
                            elif p == 1:
                                nameSpace['content']['cursorFirstRelPath'] = 'index.html'
                                nameSpace['content']['cursorPreviousRelPath'] = 'index.html'
                            if p == webNumberOfPages - 1:
                                nameSpace['content']['cursorNextRelPath'] = None
                                nameSpace['content']['cursorLastRelPath'] = None
                    nameSpace['index'] = indexMenu
                    self._generatePageWebFiles(nameSpace, templateDirPath, outputPath, langId, zoomId, frameKeys)
            if removeLastInterval:
                self.metadata[langId].index.pop()
        for dir in ['images', 'styles']:
            outputDirPath = os.path.join(outputPath, dir)
            if os.path.exists(outputDirPath):
                shutil.rmtree(outputDirPath)
            shutil.copytree(os.path.join(templateDirPath, dir), outputDirPath, ignore=shutil.ignore_patterns('.svn*'))
        #os.system('cp -R ' + os.path.join(templateDirPath, 'images') + ' ' + outputPath)
        #os.system('cp -R ' + os.path.join(templateDirPath, 'styles') + ' ' + outputPath)
        self._generateMainIndexWebpage(templateDirPath, outputPath)



    def _determine_path(self):
        """Borrowed from wxglade.py"""
        try:
            root = __file__
            if os.path.islink(root):
                root = os.path.realpath(root)
            return os.path.dirname(os.path.abspath(root))
        except:
            print "I'm sorry, but something is wrong."
            print "There is no __file__ variable. Please contact the author."
            sys.exit()



